<?php
/*
 * 
 * Created on 2007-12-05
 * Project: pl.blacksoft.tomusdrw.core
 * Filename: ./core/conf/table_mysql.php
 * Author: Tomusdrw tomusdrw@blacksoft.pl
 * 		   tomusdrw.blacksoft.pl
 * 
 */
/*
 * Obsługa mysql
 */
class db {
	private $connection, $db1, $zapytan=0;
	public $tables, $core;
	function db($server, $user, $pass, $database) {
		$this->connection=mysql_connect($server,$user,$pass);
		$this->db1=mysql_select_db($database,$this->connection);
	//	$this->core = $core;
		$this->tables = $this->sqltorow('show tables');
	}
	public function getQueryCount() {
		return $this->zapytan;
	}
	public function query($sql, $debug=OVERALL_DEBUG) {
		$this->zapytan++;
//		if ($debug==1) $this->core->add('DEBUG: ' . '#'.$this->zapytan.': '.$sql, 'warn');
		$q=mysql_query($sql,$this->connection);
		$err=mysql_error($this->connection);
		if (strlen($err)>0) trigger_error($sql.' - '.$err,E_USER_ERROR);
		return $q;
	}
	public function sqltosingle($sql,$debug=OVERALL_DEBUG) {
		$res=$this->query($sql,$debug);
		while ($row=mysql_fetch_assoc($res)) $single=$row;
		return $single;
	}
	public function sqltoarray($sql,$debug=OVERALL_DEBUG) {
		$res=$this->query($sql,$debug);
		$tab=array();
		while ($row=mysql_fetch_assoc($res)) $tab[]=$row;
		return $tab;
	}
	public function sqltorow($sql, $debug=OVERALL_DEBUG) {
		$res=$this->query($sql,$debug);
		$tab=array();
		while ($row=mysql_fetch_row($res)) $tab[]=$row;
		return $tab;
	}

	//te funkcje tylko na wewnątrz potrzebne...
	public function list_fields($table) { return mysql_list_fields($this->db_name,$table,$this->connection); }
	public function num_fields($fields) { return mysql_num_fields($fields); }
	public function field_name($field,$i) { return mysql_field_name($field,$i); }
	public function num_rows($result) { return mysql_num_rows($result); }
	public function fetch_array($result) { return mysql_fetch_assoc($result); }
	public function insert_id() { return mysql_insert_id($this->connection); }
	//koniec tylko na wewn potrzebnych fukn

	public function __destruct() {
		mysql_close($this->connection);
	}
}
class table extends Ctable implements Itable {
	public $name;
	private $core;
	private $q_count=0;
	private $db; //przechowuje klase z baza
	
	public function __construct(&$db, $table_name, $cols_name=0, $tryb='error_only') {
		$this->q_count=$db->zapytan;
		$this->v = $tryb;
		
		$this->db = $db;
//		$this->core = $db->core;
		global $_table_cols;
		$cols=$_table_cols;

		//sprawdzamy tabele	
		$table_name=PREFIX.$table_name;
		//sprawdzam czy istnieje tabulka
		$ile = count($db->tables);
		$found=false;
		for ($i=0; $i<$ile; $i++) {
			if ($db->tables[$i][0]===$table_name) {
				$found=true;
				break;
			}
		}
		
		if ($found) { //tablica juz istnieje
			$this->name=$table_name;
		} else { //tablica jeszcez nie istnieje/proba utworzenia
			$tylko_table=substr($table_name, strlen(TABLES_PREFIX));
			if ($cols_name!==0&&isset($cols[$cols_name])) 
				$tylko_table = $cols_name;
			if (isset($cols[$tylko_table])) { //wiemy jak tabulka ma wygladac
				//$this->info->add("CREATE TABLE $table_name(".$cols[$tylko_table].")",'info');
				$this->db->query('CREATE TABLE '.$table_name.'('.$cols[$tylko_table].')');
				
		$this->debug('table_no_table', $table_name, DBG_WARN, 2);
				$this->name=$table_name;
			} else { //nie dal rady utworzyc
			$this->debug('table_no_table_cant', $table_name);
			}
		}			
	}
	
	public function get($limit=0, $sort='', $order=0, $typ='assoc') { //pobiera cala tabele
		if ($typ=='headers') {
			$a = $this->db->sqltorow('SHOW COLUMNS FROM '. $this->name);
			foreach ($a as $b) {
				$c[]=$b[0];
			}
			return $c;
		}
		
		$zap = 'SELECT * FROM '.$this->name;
		if ($sort!=='') {
			$zap .= ' ORDER BY '.$sort .(($order===0)?' ASC':' DESC');
		}
		if ($limit>0) {
			$zap.= ' LIMIT 0,'.$limit;
		}
		
		$sql = $this->db->query($zap);
		if ($typ=='row') {
			while ($row = mysql_fetch_row($sql)) {
				$kolumny[]=$row;
			}
		} elseif ($typ=='assoc') {
			while ($row = mysql_fetch_assoc($sql)) {
				$kolumny[]=$row;
			}
		} else {
			while ($row = mysql_fetch_array($sql)) {
				$kolumny[]=$row;
			}
		}
		
		return $kolumny;
	}
	
	public function insert($dane) { //dopisuje dane na koniec tablicy
		$simple=false;
		if (is_array($dane)) {
			foreach ($dane as $v) {
				if (!is_array($v)) {$simple=true; break; }
			}
			$headers = $this->get(0, '', 0, 'headers');
			if ($simple&&count($dane)>0) {
				$zapytanie = 'INSERT into '.$this->tab_name.' (';
				foreach ($headers as $v) {
					if (isset($dane[$v])) {
						$zapytanie.='"'.$dane[$v].'", ';
					}
				}
				$zapytanie=substr($zapytanie, 0, strlen($zapytanie)-1).') values (';
				
				$ile = count($headers);
				for($i=0; $i<$ile; $i++) {
					$zapytanie.='"'.$dane[$headers[$i]].'", ';
				}
				$zapytanie = substr($zapytanie, 0, strlen($zapytanie)-2);
				$zapytanie.=");";
				$this->db->query($zapytanie);
			} else {
				foreach ($dane as $v) {
					$zapytanie = 'INSERT into '.$this->tab_name.' values (';
					$ile = count($headers);
					for($i=0; $i<$ile; $i++) {
						$zapytanie.='"'.$dane[$headers[$i]].'", ';
					}
					$zapytanie = substr($zapytanie, 0, strlen($zapytanie)-2);
					$zapytanie.=');';
					$this->db->query($zapytanie);
				}
			}
		//	if ($this->v!=='silent'&&$this->v!=='error_only')
			$this->debug('table_succesful_insert', null, DBG_INFO, 3);
			return $db->insert_id;
		} else {
//			if ($this->v!=='silent')
			$this->debug('table_wrong_input');
			return false;
		}
	}
	
	public function save($dane) { //zapisuje dane zwraca 0->wszystko ok 1->niepoprawne dane
		if (is_array($dane)) {
			$zap = 'delete from '.$this->tab_name;
			$this->db->query($zap);
			//mamy czysta tabele
			$headers = $this->get(0, '', 0, 'headers');
			foreach ($dane as $wiersz) {
				$zapytanie = 'INSERT into '.$this->tab_name.' values (';
				foreach ($headers as $h) {
					if ($wiersz[$h]!=='auto')
						$zapytanie.='"'.$wiersz[$h].'" ,';
				}
				$zapytanie = substr($zapytanie, 0, strlen($zapytanie)-2);
				$zapytanie.=');';
				//print $zapytanie."<br/>";
				$this->db->query($zapytanie);
			}
	//		if ($this->v!=='silent'&&$this->v!=='error_only')
		$this->debug('table_changes_saved', DBG_INFO, 4);
			return 0;
		}
///		if ($this->v!=='silent')
	$this->debug('table_wrong_input');
		return 1;
	}
	
	public function select($kolumny, $wartosci, $operatory='=', $limit=0) {
		$zap = 'SELECT * FROM '.$this->name.' where ';
		if (is_array($kolumny)&&is_array($wartosci)&&(is_array($operatory)||$operatory==='=')&&(count($kolumny)==count($wartosci))) {
			$zap.=$kolumny[0].' '.((isset($operatory[0]))?$operatory[0]:(is_array($operatory))?$operatory[count($operatory)-1]:$operatory).' "'.$wartosci[0].'"';
			for($i=1;$i<count($kolumny);$i++) {
				$zap.=' and '.$kolumny[$i].' '.((isset($operatory[$i]))?$operatory[$i]:(is_array($operatory))?$operatory[count($operatory)-1]:$operatory).' "'.$wartosci[$i].'"';	
			}
		} elseif (!is_array($kolumny)&&!is_array($wartosci)&&!is_array($operatory)) {
			$zap .= $kolumny . ' ' . $operatory .' "'.$wartosci.'"';
		} else {
	//		if ($this->v!=='silent')
		$this->debug('table_wrong_input');
			return 1;
		}
		
		$a = $this->db->sqltoarray($zap);

		if ($limit>0) {
			$ile = count($a)-1;
			$min = ($ile-$limit<0)?0:$ile-$limit;
			for ($i=$ile;$i>=$min; $i--) {
				$ret[]=$a[$i];
			}
		} else {
			$ret = $a;
		}
		unset($a);
		return $ret;
	}
	public function update($kolumny,$wartosci,$operatory='=', $dane) {
		if (!$this->delete($kolumny, $wartosci, $operatory))		
			$this->insert($dane);
		return 0;
	}
	
	public function delete($kolumny, $wartosci, $operatory='=') {
		$zap='DELETE FROM '.$this->name.' where ';
		if (is_array($kolumny)&&is_array($wartosci)&&(is_array($operatory)||$operatory==='=')&&(count($kolumny)==count($wartosci))) {
			$zap.=$kolumny[0].' '.((isset($operatory[0]))?$operatory[0]:(is_array($operatory))?$operatory[count($operatory)-1]:$operatory).' "'.$wartosci[0].'"';
			for($i=1;$i<count($kolumny);$i++) {
				$zap.=' and '.$kolumny[$i].' '.((isset($operatory[$i]))?$operatory[$i]:(is_array($operatory))?$operatory[count($operatory)-1]:$operatory).' "'.$wartosci[$i].'"';	
			}
		} elseif (!is_array($kolumny)&&!is_array($wartosci)&&!is_array($operatory)) {
			$zap .= $kolumny.' '.$operatory.' "'.$wartosci.'"';
		} else {
	//		if ($this->v!=='silent')
		$this->debug('table_wrong_input');
			return 1;
		}
		
		$zap.=";";
		//@todo karol sie zaklada ze nie bedzie dzialac
		$before=$this->db->sqltoarray('SELECT COUNT(id) AS ilosc FROM '.$this->name);
		$before=$before['ilosc'];
		
		$this->db->query($zap); //usunalem
		
		$after = $this->db->sqltoarray('SELECT COUNT(id) AS ilosc FROM '.$this->name.";");
		
		if ($before == $after['ilosc']) {
		//	if ($this->v!=='silent'&&$this->v!=='error_only')
			$this->debug('table_no_changes', null, DBG_INFO, 3);
			return 3;
		}
	//	if ($this->v!=='silent'&&$this->v!=='error_only')
		$this->debug('table_changes_saved', null, DBG_INFO, 3);
		return 0;
	}
	
}

?>